<template>
  <el-dialog
    title="发送通知"
    v-model="visible"
    width="900px"
    append-to-body
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="通知类型" prop="templateId">
        <el-select
          v-model="formData.templateId"
          placeholder="请选择"
          style="width: 100%"
          @change="handleTemplateChange"
        >
          <el-option
            v-for="item in manualNotifyTemplateList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="推送标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入推送标题"
          clearable
        />
      </el-form-item>

      <el-form-item label="推送详情" prop="content">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="4"
          placeholder="短信模版,不能改,通过下面的参数自动显示预览"
          :disabled="true"
        />
      </el-form-item>

      <el-form-item label="模板参数">
        <div class="param-list">
          <div
            v-for="(param, index) in formData.templateParam"
            :key="index"
            class="param-item"
          >
            <el-input
              v-model="param.paramKeyCode"
              placeholder="参数代码"
              style="width: 150px"
              disabled
            />
            <span class="param-separator">:</span>
            <el-input
              v-model="param.paramValue"
              :placeholder="param.paramDesc || '参数值'"
              style="flex: 1"
              @input="updatePreviewContent"
            />
          </div>
        </div>
      </el-form-item>

      <el-form-item label="附件">
        <FileUpload
          v-model="formData.attachmentFileVo"
          :limit="5"
          :file-type="['pdf', 'doc', 'docx', 'xls', 'xlsx', 'jpg', 'jpeg', 'png']"
          :file-size="50"
          title="上传附件"
        />
      </el-form-item>

      <el-form-item label="接收人">
        <div class="recipient-section">
          <div class="select-all-tags" v-if="formData.allTenantFlag === 1 || formData.allHomeownersFlag === 1">
            <el-tag
              v-if="formData.allTenantFlag === 1"
              type="success"
              closable
              @close="clearSelectAll(RECIPIENT_TYPE.TENANT)"
            >
              已选择全部租客
            </el-tag>
            <el-tag
              v-if="formData.allHomeownersFlag === 1"
              type="warning"
              closable
              @close="clearSelectAll(RECIPIENT_TYPE.LANDLORD)"
            >
              已选择全部房东
            </el-tag>
          </div>
          <el-table
            :data="formData.effectiveVo"
            style="width: 100%"
            max-height="300"
          >
            <el-table-column label="类型" align="center" prop="userType">
              <template #default="scope">
                <span>{{ getRecipientTypeText(scope.row.userType) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="接收人" align="center" prop="name" />
            <el-table-column label="手机号" align="center" prop="phone" />
            <el-table-column label="操作" align="center" width="80">
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  @click="removeRecipient(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="recipient-actions" style="margin-top: 12px">
            <el-button type="primary" @click="handleSelectTenant">选择租客</el-button>
            <el-button type="primary" @click="handleSelectLandlord">选择房东</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>

    <!-- 接收人选择弹窗 -->
    <RecipientSelectorDialog
      v-model="recipientSelectorVisible"
      :recipient-type="currentRecipientType"
      :selected-list="dialogSelectedList"
      :select-all-flag="dialogSelectAllFlag"
      @confirm="handleRecipientConfirm"
    />
  </el-dialog>
</template>

<script setup name="SendNotifyDialog">
import { ref, reactive, computed, getCurrentInstance } from 'vue'
import RecipientSelectorDialog from './RecipientSelectorDialog.vue'
import FileUpload from '@/components/FileUpload/index.vue'
import { getNotifyTemplate } from '@/api/fang/notify'
import {
  RECIPIENT_TYPE,
  MANUAL_NOTIFY_TEMPLATE_LIST,
  getRecipientTypeText
} from '@/utils/enums'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'confirm'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const formRef = ref(null)
const recipientSelectorVisible = ref(false)
const currentRecipientType = ref(RECIPIENT_TYPE.TENANT)
const manualNotifyTemplateList = MANUAL_NOTIFY_TEMPLATE_LIST
const templateContent = ref('') // 原始模板内容

const formData = reactive({
  templateId: null,
  title: '',
  content: '请选择通知类型后，模板内容将自动显示',
  templateParam: [],
  effectiveVo: [],
  attachmentFileVo: [],
  allHomeownersFlag: 0,
  allTenantFlag: 0
})

const rules = {
  templateId: [{ required: true, message: '请选择通知类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入推送标题', trigger: 'blur' }]
}

const { proxy } = getCurrentInstance()

const dialogSelectedList = computed(() => {
  return formData.effectiveVo.filter(item => item.userType === currentRecipientType.value && !item.isAll)
})

const dialogSelectAllFlag = computed(() => {
  return currentRecipientType.value === RECIPIENT_TYPE.TENANT
    ? formData.allTenantFlag === 1
    : formData.allHomeownersFlag === 1
})

// 通知模板选择变化
function handleTemplateChange(templateId) {
  if (!templateId) {
    formData.content = '请选择通知类型后，模板内容将自动显示'
    formData.templateParam = []
    templateContent.value = ''
    return
  }

  // 调用接口获取模板详情
  getNotifyTemplate(templateId)
    .then(response => {
      if (response.code === 200 || response.code === 0) {
        const data = response.data
        // 设置模板内容
        templateContent.value = data.templateContent || ''
        formData.content = templateContent.value
        
        // 设置模板参数
        if (data.templateParam && Array.isArray(data.templateParam)) {
          formData.templateParam = data.templateParam.map(param => ({
            paramKeyCode: param.paramKeyCode || '',
            paramDesc: param.paramDesc || '',
            paramValue: param.paramValue || ''
          }))
        } else {
          formData.templateParam = []
        }
        
        // 更新预览内容
        updatePreviewContent()
      } else {
        proxy.$modal.msgError(response.msg || '获取模板详情失败')
      }
    })
    .catch(error => {
      console.error('获取模板详情失败:', error)
      proxy.$modal.msgError('获取模板详情失败')
    })
}

// 更新预览内容（根据参数值替换模板中的占位符）
function updatePreviewContent() {
  if (!templateContent.value) {
    return
  }
  
  let content = templateContent.value
  // 替换模板中的参数占位符 ${paramKeyCode}
  // 如果参数值为空，保留占位符显示，让用户知道这里可以填入信息
  formData.templateParam.forEach(param => {
    const placeholder = `\${${param.paramKeyCode}}`
    if (param.paramValue && param.paramValue.trim()) {
      // 有值则替换
      content = content.replace(new RegExp(placeholder.replace(/\$/g, '\\$'), 'g'), param.paramValue)
    }
    // 无值则保留占位符，不进行替换
  })
  
  formData.content = content
}

// 选择租客
function handleSelectTenant() {
  currentRecipientType.value = RECIPIENT_TYPE.TENANT
  recipientSelectorVisible.value = true
}

// 选择房东
function handleSelectLandlord() {
  currentRecipientType.value = RECIPIENT_TYPE.LANDLORD
  recipientSelectorVisible.value = true
}

// 接收人选择确认
function handleRecipientConfirm(payload) {
  const { selectAll, recipients } = payload
  const type = currentRecipientType.value

  if (type === RECIPIENT_TYPE.TENANT) {
    formData.allTenantFlag = selectAll ? 1 : 0
  } else {
    formData.allHomeownersFlag = selectAll ? 1 : 0
  }

  // 先移除当前类型已存在的数据
  formData.effectiveVo = formData.effectiveVo.filter(item => item.userType !== type)

  const mapped = recipients.map(recipient => transformRecipient(recipient, type))
  formData.effectiveVo.push(...mapped)
}

// 删除接收人
function removeRecipient(row) {
  const index = formData.effectiveVo.indexOf(row)
  if (index > -1) {
    formData.effectiveVo.splice(index, 1)
  }

  if (row.userType === RECIPIENT_TYPE.TENANT) {
    if (formData.allTenantFlag === 1 && formData.effectiveVo.filter(item => item.userType === RECIPIENT_TYPE.TENANT).length > 0) {
      formData.allTenantFlag = 0
    }
  } else if (row.userType === RECIPIENT_TYPE.LANDLORD) {
    if (formData.allHomeownersFlag === 1 && formData.effectiveVo.filter(item => item.userType === RECIPIENT_TYPE.LANDLORD).length > 0) {
      formData.allHomeownersFlag = 0
    }
  }
}

// 确定按钮
function handleConfirm() {
  formRef.value.validate((valid) => {
    if (valid) {
      if (
        formData.effectiveVo.length === 0 &&
        formData.allTenantFlag === 0 &&
        formData.allHomeownersFlag === 0
      ) {
        proxy.$modal.msgWarning('请至少选择一个接收人')
        return
      }
      // 过滤掉已选择全部的类型成员
      const filteredEffectiveVo = formData.effectiveVo.filter(item => {
        if (formData.allTenantFlag === 1 && item.userType === RECIPIENT_TYPE.TENANT) {
          return false
        }
        if (formData.allHomeownersFlag === 1 && item.userType === RECIPIENT_TYPE.LANDLORD) {
          return false
        }
        return true
      })
      
      const payload = {
        templateId: formData.templateId,
        title: formData.title,
        content: formData.content,
        templateParam: formData.templateParam.map(param => ({
          paramDesc: param.paramDesc,
          paramKeyCode: param.paramKeyCode,
          paramValue: param.paramValue
        })),
        effectiveVo: filteredEffectiveVo.map(item => ({
          homeownersId: item.homeownersId,
          leaseContractId: item.leaseContractId,
          name: item.name,
          phone: item.phone,
          userType: item.userType
        })),
        attachmentFileVo: (formData.attachmentFileVo || []).map(mapAttachment),
        allHomeownersFlag: formData.allHomeownersFlag,
        allTenantFlag: formData.allTenantFlag
      }
      emit('confirm', payload)
      handleClose()
    }
  })
}

// 关闭弹窗
function handleClose() {
  visible.value = false
  // 重置表单
  formData.templateId = null
  formData.title = ''
  formData.content = '请选择通知类型后，模板内容将自动显示'
  formData.templateParam = []
  formData.effectiveVo = []
  formData.attachmentFileVo = []
  formData.allHomeownersFlag = 0
  formData.allTenantFlag = 0
  templateContent.value = ''
  formRef.value?.resetFields()
}

function mapAttachment(file) {
  const filePath = file.url || file.filePath
  const originalName = file.originalName || file.name || file.fileName
  return {
    fileName: file.fileName || originalName,
    originalName,
    filePath,
    fileSize: file.size || file.fileSize || 0,
    fileType: file.fileType || (originalName && originalName.split('.').pop()) || '',
    id: file.id
  }
}

function transformRecipient(recipient, type) {
  return {
    targetId: recipient.id ?? recipient.targetId ?? null,
    homeownersId: recipient.homeownersId ?? (type === RECIPIENT_TYPE.LANDLORD ? recipient.id : null) ?? null,
    leaseContractId: recipient.leaseContractId ?? (type === RECIPIENT_TYPE.TENANT ? recipient.id : null) ?? null,
    name: recipient.name,
    phone: recipient.phone || '',
    userType: type
  }
}

function clearSelectAll(type) {
  if (type === RECIPIENT_TYPE.TENANT) {
    formData.allTenantFlag = 0
    formData.effectiveVo = formData.effectiveVo.filter(item => item.userType !== RECIPIENT_TYPE.TENANT)
  } else {
    formData.allHomeownersFlag = 0
    formData.effectiveVo = formData.effectiveVo.filter(item => item.userType !== RECIPIENT_TYPE.LANDLORD)
  }
}
</script>

<style scoped>
.param-list {
  width: 100%;
}

.param-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.param-separator {
  margin: 0 4px;
}

.recipient-section {
  width: 100%;
}

.select-all-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}
</style>

